import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        cartList: [],
        checkedAll: true,
        allPrice: 0,
        checked: 0,
    },
    mutations: {
        addCart(state, payload) {
            state.cartList.push(payload)
        },
        changecheckedAll(state) {
            let flag = 0;
            for (let item of state.cartList) {
                if (item.isChecked != true) {
                    state.checkedAll = false;
                    flag = 1;
                    break;
                }
            }
            if (flag == 0) {
                state.checkedAll = true;
            }
        },
        sumChecked(state) {
            state.checked = 0;
            for (let item of state.cartList) {
                if (item.isChecked) {
                    state.checked++;
                }
            }
        },
        sumPrice(state) {
            state.allPrice = 0;
            for (let item of state.cartList) {
                if (item.isChecked) {
                    state.allPrice += item.price * item.count;
                }
            }
        },
        addCount(state, payload) {
            payload.count++;
        },
        subCount(state, payload) {
            payload.count--;
        },
        delete(state, payload) {
            state.cartList.splice(payload, 1);
        },
    },
    actions: {
        selectAll(context) {
            context.state.checkedAll = !context.state.checkedAll;
            for (let item of context.state.cartList) {
                item.isChecked = context.state.checkedAll;
            }
            context.commit('sumChecked');
            context.commit('sumPrice');
        },
        changeIsChecked(context, payload) {
            payload.isChecked = !payload.isChecked;
            context.commit('changecheckedAll');
            context.commit('sumChecked');
            context.commit('sumPrice');
        },
        compile(context) {
            for (let item of context.state.cartList) {
                if (item.isChecked == true) {
                    item.isChecked = false;
                    item.flag = true;
                }
            }
            context.commit('changecheckedAll');
            context.commit('sumChecked');
        },
        accomplish(context) {
            for (let item of context.state.cartList) {
                if (item.flag == true) {
                    item.isChecked = true;
                    item.flag = false;
                }
            }
            context.commit('changecheckedAll');
            context.commit('sumChecked');
            context.commit('sumPrice');
        },
        deleteItem(context, payload) {
            context.commit('delete', payload);
            context.commit('sumChecked');
        },
    },
    modules: {}
})